<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\SystemSetting;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ProcessOrderAutomation extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'orders:automation 
                            {--timeout=30 : 订单超时时间（分钟）}
                            {--dry-run : 仅模拟运行，不执行实际操作}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '处理订单自动化任务：超时取消、状态更新等';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $timeout = (int) $this->option('timeout');
        $dryRun = $this->option('dry-run');
        
        $this->info("开始处理订单自动化任务...");
        $this->info("超时时间: {$timeout}分钟");
        $this->info("运行模式: " . ($dryRun ? '模拟运行' : '实际执行'));

        $processedCount = 0;

        // 1. 处理超时未支付订单
        $processedCount += $this->processTimeoutOrders($timeout, $dryRun);
        
        // 2. 处理长时间未发货订单
        $processedCount += $this->processLongPendingOrders($dryRun);
        
        // 3. 处理长时间未确认收货订单
        $processedCount += $this->processLongShippedOrders($dryRun);

        $this->info("自动化处理完成，共处理 {$processedCount} 个订单");
        
        return Command::SUCCESS;
    }

    /**
     * 处理超时未支付订单
     */
    private function processTimeoutOrders(int $timeout, bool $dryRun): int
    {
        $timeoutDate = now()->subMinutes($timeout);
        
        $orders = Order::where('status', Order::STATUS_PENDING)
            ->where('payment_status', Order::PAYMENT_PENDING)
            ->where('created_at', '<', $timeoutDate)
            ->get();

        $count = 0;
        
        foreach ($orders as $order) {
            $this->line("处理超时订单: {$order->order_number}");
            
            if (!$dryRun) {
                try {
                    $order->updateStatus([
                        'status' => Order::STATUS_CANCELLED,
                        'cancelled_at' => now(),
                        'cancel_reason' => "系统自动取消：超过{$timeout}分钟未支付"
                    ], '自动取消', "超时{$timeout}分钟未支付", '系统');
                    
                    $count++;
                    $this->info("✓ 已取消订单: {$order->order_number}");
                    
                    // 记录日志
                    Log::info("订单自动取消", [
                        'order_number' => $order->order_number,
                        'user_id' => $order->user_id,
                        'timeout_minutes' => $timeout,
                        'created_at' => $order->created_at,
                    ]);
                } catch (\Exception $e) {
                    $this->error("✗ 取消订单失败: {$order->order_number} - {$e->getMessage()}");
                    Log::error("订单自动取消失败", [
                        'order_number' => $order->order_number,
                        'error' => $e->getMessage(),
                    ]);
                }
            } else {
                $this->line("  [模拟] 将取消订单: {$order->order_number}");
                $count++;
            }
        }

        if ($count > 0) {
            $this->info("处理了 {$count} 个超时未支付订单");
        }

        return $count;
    }

    /**
     * 处理长时间未发货订单
     */
    private function processLongPendingOrders(bool $dryRun): int
    {
        // 超过24小时未发货的已支付订单
        $longPendingDate = now()->subHours(24);
        
        $orders = Order::where('status', Order::STATUS_PROCESSING)
            ->where('payment_status', Order::PAYMENT_PAID)
            ->where('paid_at', '<', $longPendingDate)
            ->get();

        $count = 0;
        
        foreach ($orders as $order) {
            $this->line("处理长时间未发货订单: {$order->order_number}");
            
            if (!$dryRun) {
                // 这里可以发送提醒通知给管理员
                Log::warning("订单长时间未发货", [
                    'order_number' => $order->order_number,
                    'user_id' => $order->user_id,
                    'paid_at' => $order->paid_at,
                    'hours_pending' => $order->paid_at->diffInHours(now()),
                ]);
            } else {
                $this->line("  [模拟] 将提醒管理员: {$order->order_number}");
            }
            
            $count++;
        }

        if ($count > 0) {
            $this->info("发现 {$count} 个长时间未发货订单");
        }

        return $count;
    }

    /**
     * 处理长时间未确认收货订单
     */
    private function processLongShippedOrders(bool $dryRun): int
    {
        // 从系统设置读取自动确认天数
        $autoConfirmDays = (int) SystemSetting::get('auto_confirm_days', 7);
        $longShippedDate = now()->subDays($autoConfirmDays);
        
        $orders = Order::where('status', Order::STATUS_SHIPPED)
            ->where('shipped_at', '<', $longShippedDate)
            ->get();

        $count = 0;
        
        foreach ($orders as $order) {
            $this->line("处理长时间未确认收货订单: {$order->order_number}");
            
            if (!$dryRun) {
                try {
                    // 自动标记为已送达
                    $order->updateStatus([
                        'status' => Order::STATUS_DELIVERED,
                        'delivered_at' => now(),
                    ], '自动确认收货', "超过{$autoConfirmDays}天未确认，系统自动确认", '系统');
                    
                    $count++;
                    $this->info("✓ 已自动确认收货: {$order->order_number}");
                    
                    Log::info("订单自动确认收货", [
                        'order_number' => $order->order_number,
                        'user_id' => $order->user_id,
                        'shipped_at' => $order->shipped_at,
                        'days_shipped' => $order->shipped_at->diffInDays(now()),
                    ]);
                } catch (\Exception $e) {
                    $this->error("✗ 自动确认收货失败: {$order->order_number} - {$e->getMessage()}");
                    Log::error("订单自动确认收货失败", [
                        'order_number' => $order->order_number,
                        'error' => $e->getMessage(),
                    ]);
                }
            } else {
                $this->line("  [模拟] 将自动确认收货: {$order->order_number}");
                $count++;
            }
        }

        if ($count > 0) {
            $this->info("处理了 {$count} 个长时间未确认收货订单");
        }

        return $count;
    }
}